//
//  FQDSegmentedControl.m
//  FakeQDaily
//
//  Created by mewxiv on 9/20/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDSegmentedControl.h"

@interface FQDSegmentedControl ()
@property (nonatomic, assign) CGFloat segmentWidth;
@property (nonatomic, strong) NSArray *sectionWidths;
@property (nonatomic, strong) CALayer *selectLineIndicator;
@end

@implementation FQDSegmentedControl

#pragma mark - View life Cycle
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self parepareUI];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self parepareUI];
    }
    return self;
}

- (instancetype)initWithSectionTitles:(NSArray *)titles
{
    self = [self initWithFrame:CGRectZero];
    if (self) {
        [self parepareUI];
        _sectionTitles = titles;
        
        [self updateSectionWidths];
    }
    
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self parepareUI];
}

- (void)parepareUI
{
    
    _backgroundColor = [UIColor whiteColor];
    _selectIndicatorColor = [UIColor blackColor];
    _selectLineIndicatorHeight = 5.0f;
    _selectIndicatorWidthStyle = FQDSegmentedControlSelectIndicatorWidthStyleFixed;
    _selectIndicatorFixedWidthRatio = 0.5f;
    self.selectedSegmentIndex = 0;
    
    NSMutableParagraphStyle *paraStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    paraStyle.alignment = NSTextAlignmentCenter;
    paraStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    
    _sectionTitleAttributes = @{
        NSFontAttributeName : [UIFont systemFontOfSize:18],
        NSParagraphStyleAttributeName : paraStyle,
    };
    
    _selectedSectionTitleAttributes = @{
        NSFontAttributeName : [UIFont systemFontOfSize:18],
        NSParagraphStyleAttributeName : paraStyle,
    };
    
    _selectLineIndicator = [CALayer layer];
    _selectLineIndicator.backgroundColor = [_selectIndicatorColor CGColor];
    [self.layer addSublayer:_selectLineIndicator];
    
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self updateSectionWidths];
    [self updateSelectIndicatorFrame];
    [self setNeedsDisplay];
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    if (newSuperview == nil) {
        return;
    }
}

#pragma mark - View Property Setters

- (void)setSectionTitles:(NSArray *)sectionTitles
{
    _sectionTitles = sectionTitles;
    
    [self updateSectionWidths];
    [self setNeedsDisplay];
}

- (void)setSelectIndicatorColor:(UIColor *)selectIndicatorColor
{
    _selectIndicatorColor = selectIndicatorColor;
    
    self.selectLineIndicator.backgroundColor = [selectIndicatorColor CGColor];
    [self setNeedsLayout];
}

- (void)setSelectedSegmentIndex:(NSInteger)selectedSegmentIndex
{
    if (_selectedSegmentIndex == selectedSegmentIndex ) {
        return;
    }
    _selectedSegmentIndex = selectedSegmentIndex;
    
    self.selectedIndexChangedBlock ? self.selectedIndexChangedBlock(selectedSegmentIndex) : nil;
    [self setNeedsLayout];
}

#pragma mark - Touch Event Methods
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    
    [self.sectionTitles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGRect segmentRect = CGRectMake(idx * self.segmentWidth, 0, self.segmentWidth, self.bounds.size.height);
        if (CGRectContainsPoint(segmentRect, location)) {
            [self setSelectedSegmentIndex:idx];
            *stop = YES;
        }
    }];
}

#pragma mark - Drawing

- (void)drawRect:(CGRect)rect
{
    [self.backgroundColor setFill];
    UIRectFill(self.bounds);
    
    [self.sectionTitles enumerateObjectsUsingBlock:^(NSString * _Nonnull titleString, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *attributes;
        if (idx == self.selectedSegmentIndex) {
            attributes = [self selectedSectionTitleAttributes];
        } else {
            attributes = [self sectionTitleAttributes];
        }
        CGFloat titleHeight = roundf([self sizeForSectionTitleAtIndex:idx].height);
        
        CGFloat y = (self.frame.size.height - titleHeight) / 2;
        CGRect stringRect = CGRectMake(idx * self.segmentWidth, y, self.segmentWidth, titleHeight);
        [titleString drawInRect:stringRect withAttributes:attributes];
      
    }];
}

- (CGSize)sizeForSectionTitleAtIndex:(NSInteger)index
{
    NSString *sectionTitle = [self.sectionTitles objectAtIndex:index];
    NSDictionary *attributes;
    if (index == self.selectedSegmentIndex) {
        attributes = [self selectedSectionTitleAttributes];
    } else {
        attributes = [self sectionTitleAttributes];
    }
    return [sectionTitle sizeWithAttributes:attributes];
}

- (void)updateSectionWidths {
    self.segmentWidth = self.layer.frame.size.width / [self.sectionTitles count];
    
    NSMutableArray *mutableSectionWidths = [NSMutableArray array];
    [self.sectionTitles enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        CGSize size = [self sizeForSectionTitleAtIndex:idx];
        [mutableSectionWidths addObject:@(size.width)];
    }];
    self.sectionWidths = [mutableSectionWidths copy];
}

- (void)updateSelectIndicatorFrame
{
    NSInteger selectedSegmentIndex = self.selectedSegmentIndex;
    if ([self.sectionTitles count] > 0) {
        CGFloat width = 0;
        if (_selectIndicatorWidthStyle == FQDSegmentedControlSelectIndicatorWidthStyleFixed) {
            width = self.selectIndicatorFixedWidthRatio * self.segmentWidth;
        } else {
            CGFloat sectionWidth = [[self.sectionWidths objectAtIndex:selectedSegmentIndex] floatValue];
            width = MIN(sectionWidth, self.segmentWidth);
        }
        CGFloat x = (selectedSegmentIndex * self.segmentWidth) + (self.segmentWidth - width) / 2;
        CGFloat y = self.bounds.size.height - self.selectLineIndicatorHeight;
        self.selectLineIndicator.frame = CGRectIntegral(CGRectMake(x, y, width, self.selectLineIndicatorHeight));
    } else {
        self.selectLineIndicator.frame = CGRectZero;
    }
}

@end
